<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="username">
            <UserSelect v-model="form.username" :placeholder="$t('申请人')" @change="changeName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请部门')" prop="deptId">
            <DeptSelect v-model="form.deptId" :placeholder="$t('申请部门')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('岗位/职务')" prop="postId">
            <el-select v-model="form.postIds" multiple :placeholder="$t('请选择')">
              <el-option
                v-for="item in postOptions"
                :key="item.postId"
                :label="$t(item.postName)"
                :value="item.postId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applyTime">
            <el-date-picker
              v-model="form.applyTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('申请时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('开始时间')" prop="startDate">
            <el-date-picker
              v-model="form.startDate"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('开始时间')"
              :picker-options="pickerOptionStart"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('结束时间')" prop="endDate">
            <el-date-picker
              v-model="form.endDate"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('结束时间')"
              :picker-options="pickerOptionEnd"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('加班天数')" prop="applicationDuration">
            <el-select v-model="form.applicationDuration" filterable :placeholder="$t('加班天数')">
              <el-option
                v-for="dict in applicationDurations"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('加班原因')" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('加班原因')" />
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable :list.sync="form.fileList" data-type="anxin_overtime" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="anxin:overtime" :menu-key="menuKey" />
    </div>
  </div>
</template>

<script>
import {
  saveAnxinOvertimeApplication,
  getAnxinOvertimeApplication
} from '@/api/anxin/overtime/anxinOvertimeApplication'
import { listPost } from '@/api/system/post'
import { getUser } from '@/api/system/user'

export default {
  components: {
  },
  data() {
    return {
      // 菜单标识
      menuKey: 'anxin_overtime',
      // 加班天数
      applicationDurations: [],
      // 表单参数
      form: {
        id: undefined,
        postId: [],
        startDate: '',
        endDate: ''
      },
      // 控制开始时间不能在结束时间之后
      pickerOptionStart: {
        disabledDate: time => {
          if (this.form.endDate) {
            return (
              time.getTime() >
              new Date(this.form.endDate).getTime()
            )
          }
        }
      },
      // 控制结束时间不能在开始时间之前
      pickerOptionEnd: {
        disabledDate: time => {
          if (this.form.startDate) {
            return (
              time.getTime() <
              new Date(this.form.startDate).getTime() - 86399999
            )
          }
        }
      },
      // 表单校验
      rules: {
        username: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        actTitle: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        applicationDuration: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        startDate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        endDate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      // 岗位选项
      postOptions: [],
      // 遮罩层
      loading: false,
      // 是否隐藏其它按钮
      otherBtnHide: false,
      // 操作按钮默认不展示
      buttonShow: true,
      // 开始时间
      startDatePicker: this.beginDate(),
      // 结束时间
      endDatePicker: this.processDate()
    }
  },
  // watch: {
  //   'form.username': {
  //     handler(val) {
  //       if (val === undefined || val === null || val === '' || !this.isChange) {
  //         return
  //       }
  //       getUser(this.form.username).then(response => {
  //         this.$set(this.form, 'postIds', response.datas.postIds)
  //         this.$set(this.form, 'deptId', response.data.deptId)
  //       })
  //     },
  //     deep: true,
  //     immediate: true
  //   }
  // },
  created() {
    this.initDict()
    this.$bus.$emit('async_done')
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getAnxinOvertimeApplication(data.id).then(response => {
          this.form = response.data
          this.loading = false
        })
      } else {
        this.reset()
        this.form.username = this.$store.state.user.userId
        this.loading = false
        this.changeName()
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        username: undefined,
        applicationDuration: undefined,
        actId: undefined,
        actStatus: undefined,
        actTitle: undefined,
        startDate: this.parseTime(new Date()),
        endDate: undefined,
        remark: undefined,
        postIds: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      }
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function(type) {
      return new Promise((resolve) => {
        this.$refs['form'].validate(valid => {
          // 验证数据
          if (valid) {
            // 弹出遮罩层
            this.loading = true
            // 保存数据
            saveAnxinOvertimeApplication(this.form).then(response => {
              if (response.code === 200) {
                // 点击的按钮是保存并启动流程
                if (type === 'process') {
                  // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                  this.form.id = response.data.id
                  // 启动流程
                  this.startProcess(response.data.id)
                  // 点击的仅保存
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  // 关闭form页面
                  this.closeForm()
                }
                resolve()
              } else {
                this.msgError(response.msg)
                this.loading = false
              }
            }).catch(() => {
              this.loading = false
            })
          } else {
            this.locationError(document)
          }
        })
      })
    },
    startDateChange(val) {
      if (val > this.form.endDate) {
        this.msgError(this.$t('开始时间不能大于结束时间'))
        this.form.endDate = undefined
        return
      }
      this.vacationDays()
    },
    endDateChange(val) {
      if (this.form.startDate > val) {
        this.msgError(this.$t('开始时间不能大于结束时间'))
        this.form.endDate = undefined
        return
      }
      this.vacationDays()
    },
    beginDate() {
      const self = this
      return {
        disabledDate(time) {
          if (self.form.endDate) {
            // 如果结束时间不为空，则小于结束时间
            return new Date(self.form.endDate).getTime() < time.getTime() || time.getTime() < Date.now() - 1000 * 3600 * 24
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
            // 开始时间不选时，结束时间最大值小于等于当天
            return time.getTime() < Date.now() - 1000 * 3600 * 24
          }
        }
      }
    },
    processDate() {
      const self = this
      return {
        disabledDate(time) {
          if (self.form.startDate) {
            // 如果开始时间不为空，则结束时间大于开始时间
            return new Date(self.form.startDate).getTime() >= time.getTime()
          } else {
            // 开始时间不选时，结束时间最大值小于等于当天
            return time.getTime() < Date.now() - 1000 * 3600 * 24
          }
        }
      }
    },
    // 启动流程
    startProcess: function(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.actTitle
      // 业务表名
      processData.dataTable = 'anxin_overtime_application'
      // 业务ID
      processData.dataId = dataId
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/anxin/overtime/anxinOvertimeApplicationForm'
      processData.viewPath = '@/views/anxin/overtime/anxinOvertimeApplicationView'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    initDict() {
      listPost({}).then(res => {
        this.postOptions = res.rows
      })
      this.getDicts('application_duration').then(response => {
        this.applicationDurations = response.data
      })
    },
    changeName() {
      getUser(this.form.username).then(response => {
        this.$set(this.form, 'postIds', response.datas.postIds)
        this.$set(this.form, 'deptId', response.data.deptId)
      })
    }

  }

}
</script>
